<template>
    <view>
        <TopNavigation title="报名情况" backText="赛程列表" :titleSub='"赛程:" + scheduleName' />
        <view class="view-container">
            <view class="view-container-right">
                <BoxView :titBoxObj="{
                    title: '报名记录',
                    titleCount: `共有${registrationList.length}个报名记录`
                }" padding="0" style="background: #FFFFF4;">
                    <view class="view-container-right-list">
                        <view class="view-container-right-list-item-empty"
                            v-if="registrationList.length === 0 && !isAddingNewRegistration && !loading">
                            <text>暂无报名记录</text>
                        </view>
                        <view class="view-container-right-list-item-empty" v-if="loading">
                            <text>加载中...</text>
                        </view>
                        <view v-if="!loading && registrationList.length > 0" class="view-container-right-list-item"
                            :class="{ 'view-container-right-list-item-editing': editingRegistrationId === registration.id }"
                            v-for="registration in registrationList" :key="registration.id">
                            <view class="view-container-right-list-item-title">
                                <!-- 编辑状态 -->
                                <template v-if="editingRegistrationId === registration.id">
                                    <view class="next-row">
                                        <view class="id-text"><text class="registration-id-disabled">报名ID：</text><text class="registration-id-disabled">{{ registration.id }}</text></view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-value" style="width: 50%;">
                                            <text class="form-label">用户ID：</text>
                                            <input v-model="registrationForm.userId" placeholder="请输入用户ID" class="form-input" />
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">状态：</text>
                                            <text class="registration-status-text">{{ getStatusText(registration.delFlag) }}</text>
                                        </view>
                                    </view>
                                    <view class="next-button">
                                        <view class="next-button-item1" @click.stop="saveRegistration">保存</view>
                                        <view class="next-button-item2" @click.stop="cancelEditRegistration">取消</view>
                                    </view>
                                </template>
                                <!-- 查看状态 -->
                                <template v-else>
                                    <view class="next-row">
                                        <view class="id-text"><text>报名ID：</text>{{ registration.id }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-value"><text>用户ID：</text>{{ registration.userId || '未知' }}</view>
                                        <view class="id-text"><text>状态：</text>
                                            <text class="registration-status" :class="getStatusClass(registration.delFlag)">
                                                {{ getStatusText(registration.delFlag) }}
                                            </text>
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text"><text>赛程ID：</text>{{ registration.matchScheduleId }}</view>
                                        <view class="id-text"><text>报名时间：</text>{{ formatDate(registration.createTime) }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text"><text>更新时间：</text>{{ formatDate(registration.updateTime) }}</view>
                                    </view>
                                    <view class="next-button">
                                        <view class="next-button-item1" @click.stop="editRegistration(registration)">编辑</view>
                                        <view class="next-button-item2" @click.stop="deleteRegistration(registration)">删除</view>
                                    </view>
                                </template>
                            </view>
                        </view>
                    </view>

                </BoxView>
            </view>
        </view>
        
        <!-- 删除确认弹窗 -->
        <PopuleView
            v-model="showDeleteConfirm"
            title="确认删除"
            :description="deleteConfirmText"
            :show-submit="true"
            submit-text="确认删除"
            @submit="confirmDelete"
        />
    </view>

</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchScheduleRegAPI } from '@/api/battle.js'
import BoxView from "@/components/UiView/BoxView.vue";
import TopNavigation from "@/components/UiView/TopNavigation.vue";
import PopuleView from "@/components/UiView/PopuleView.vue";

const loading = ref(false)
const registrationList = ref([])
const scheduleId = ref('')
const scheduleName = ref('')

// 报名表单相关数据
const submitting = ref(false)
const isEditingRegistration = ref(false)
const currentRegistration = ref(null)
const editingRegistrationId = ref(null) // 正在编辑的报名ID

// 新增报名相关
const isAddingNewRegistration = ref(false)

// 删除确认相关
const showDeleteConfirm = ref(false)
const currentDeleteRegistration = ref(null)
const deleteConfirmText = computed(() => {
    if (!currentDeleteRegistration.value) return ''
    const regId = currentDeleteRegistration.value.id
    return `确定要删除报名记录 ${regId} 吗？`
})

// 报名表单数据
const registrationForm = ref({
    matchScheduleRegId: '',
    matchScheduleId: '',
    userId: ''
})

// 状态映射
const statusMap = {
    0: '有效',
    1: '已删除'
}

const statusClassMap = {
    0: 'status-valid',
    1: 'status-deleted'
}

// 获取状态文本
const getStatusText = (delFlag) => statusMap[delFlag] || '未知'

// 获取状态样式
const getStatusClass = (delFlag) => statusClassMap[delFlag] || 'status-unknown'

// 格式化日期
const formatDate = (timestamp) => {
    if (!timestamp) return '未设置'
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN')
}

// 加载报名列表
const loadRegistrationList = async () => {
    if (!scheduleId.value) return
    loading.value = true
    try {
        console.log('加载报名列表，赛程ID:', scheduleId.value)
        
        const result = await MatchScheduleRegAPI.page({
            matchScheduleId: scheduleId.value,
            pageNum: 0,
            pageSize: 100
        })
        
        console.log('报名列表API返回结果:', result)
        
        if (result.code === 0) {
            registrationList.value = result.data?.list || result.data || []
            console.log('获取到报名记录:', registrationList.value)
        } else {
            registrationList.value = []
            throw new Error(result.msg || '获取报名记录失败')
        }
    } catch (error) {
        console.error('获取报名记录失败:', error)
        uni.showToast({
            title: error.message || '获取报名记录失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 打开编辑报名记录
const editRegistration = (registration) => {
    editingRegistrationId.value = registration.id
    currentRegistration.value = registration
    fillRegistrationForm(registration)
    isEditingRegistration.value = true
}

// 取消编辑报名记录
const cancelEditRegistration = () => {
    editingRegistrationId.value = null
    currentRegistration.value = null
    isEditingRegistration.value = false
    resetRegistrationForm()
}

// 重置报名表单
const resetRegistrationForm = () => {
    registrationForm.value = {
        matchScheduleRegId: '',
        matchScheduleId: '',
        userId: ''
    }
}

// 填充报名表单
const fillRegistrationForm = (registration) => {
    registrationForm.value = {
        matchScheduleRegId: registration.id || registration.matchScheduleRegId,
        matchScheduleId: registration.matchScheduleId || scheduleId.value,
        userId: registration.userId || ''
    }
}

// 保存报名记录
const saveRegistration = async () => {
    // 表单验证
    if (!registrationForm.value.userId.trim()) {
        uni.showToast({
            title: '请输入用户ID',
            icon: 'none'
        })
        return
    }
    
    submitting.value = true
    try {
        let result
        if (isEditingRegistration.value && currentRegistration.value) {
            result = await MatchScheduleRegAPI.edit({
                matchScheduleRegId: registrationForm.value.matchScheduleRegId,
                matchScheduleId: registrationForm.value.matchScheduleId,
                userId: registrationForm.value.userId
            })
        } else {
            result = await MatchScheduleRegAPI.create({
                matchScheduleId: registrationForm.value.matchScheduleId,
                userId: registrationForm.value.userId
            })
        }

        if (result.code === 0) {
            uni.showToast({
                title: isEditingRegistration.value ? '更新成功' : '创建成功',
                icon: 'success'
            })
            
            // 清除编辑状态
            isAddingNewRegistration.value = false
            editingRegistrationId.value = null
            isEditingRegistration.value = false
            currentRegistration.value = null
            resetRegistrationForm()
            
            loadRegistrationList()
        } else {
            throw new Error(result.msg || (isEditingRegistration.value ? '更新失败' : '创建失败'))
        }
    } catch (error) {
        console.error('保存报名记录失败:', error)
        uni.showToast({
            title: error.message || '保存失败',
            icon: 'none'
        })
    } finally {
        submitting.value = false
    }
}

// 删除报名记录
const deleteRegistration = (registration) => {
    currentDeleteRegistration.value = registration
    showDeleteConfirm.value = true
}

// 确认删除
const confirmDelete = async () => {
    if (!currentDeleteRegistration.value) return
    
    try {
        const result = await MatchScheduleRegAPI.remove({
            matchScheduleRegId: currentDeleteRegistration.value.id
        })
        
        if (result.code === 0) {
            uni.showToast({
                title: '删除成功',
                icon: 'success'
            })
            showDeleteConfirm.value = false
            currentDeleteRegistration.value = null
            loadRegistrationList()
        } else {
            throw new Error(result.msg || '删除失败')
        }
    } catch (error) {
        console.error('删除报名记录失败:', error)
        uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
        })
    }
}

// 页面加载
onLoad((options) => {
    if (options.scheduleId) {
        scheduleId.value = options.scheduleId
    }
    if (options.scheduleName) {
        scheduleName.value = decodeURIComponent(options.scheduleName)
    }
})

// 页面挂载时加载数据
onMounted(() => {
    loadRegistrationList()
})
</script>
<style lang="scss" scoped>
.view-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 65rpx);
    padding: 0 20rpx;
    overflow: hidden;


    .form-label {
        font-size: 12rpx;
        color: #333;
    }
    
    .registration-id-disabled {
        color: #999 !important;
        font-size: 14rpx;
    }
    
    .registration-status {
        display: inline-block;
        padding: 4rpx 12rpx;
        border-radius: 8rpx;
        font-size: 12rpx;
        font-weight: bold;
        
        &.status-valid {
            background: #d4edda;
            color: #155724;
        }
        
        &.status-deleted {
            background: #f8d7da;
            color: #721c24;
        }
    }
    
    .registration-status-text {
        font-size: 14rpx;
        color: #333;
    }

    &-right {
        flex: 1;
        height: 100%;
        overflow: hidden;
        position: relative;

        &-list {
            padding: 10rpx;
            overflow: auto;
            height: calc(100% - 60rpx);

            &-item-editing {
                background: #FFF9E6;
                border: 2rpx solid #3D85EC;
            }

            &-item {
                background: #F0F0E4;
                border-radius: 10rpx;
                padding: 10rpx;
                margin-bottom: 10rpx;
                font-size: 14rpx;

                &-empty {
                    text-align: center;
                    margin-top: 80rpx;
                }


                .next-button {
                    display: flex;
                    justify-content: end;
                    align-items: center;
                    margin-top: 10rpx;

                    &-item1,
                    &-item2 {
                        width: 108rpx;
                        height: 30rpx;
                        font-size: 14rpx;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        padding-bottom: 4rpx;
                        color: #fff;
                    }


                    &-item1 {
                        background: url('/static/buttons/button2-1.png') no-repeat center center;
                        background-size: 100% 100%;
                        margin-right: 10rpx;
                    }

                    &-item2 {
                        background: url('/static/buttons/button7.png') no-repeat center center;
                        background-size: 100% 100%;
                    }
                }

                .next-row {
                    display: flex;
                    //   justify-content: space-between;
                    align-items: center;
                    margin-top: 10rpx;

                    view {
                        width: 50%;
                        display: flex;
                        align-items: center;
                    }

                    text {
                        display: inline-block;
                        font-size: 14rpx;
                        color: #99A1A4;
                        width: 70rpx;
                        text-align: right;
                        flex-shrink: 0;
                    }
                }

                .form-input {
                    flex: 1;
                    height: 30rpx;
                    padding: 0 5rpx;
                    background: #fff;
                    border-radius: 4rpx;
                    font-size: 12rpx;
                    margin-left: 10rpx;
                    margin-right: 20rpx;
                    box-sizing: border-box;
                }
            }
        }
    }

}
</style>
